<html>
<head>
    <meta charset="UTF-8"/>
    <title>Stomp 测试</title>
    <script src="https://lib.baomitu.com/sockjs-client/1.4.0/sockjs.min.js"></script>
    <script src="https://lib.baomitu.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://lib.baomitu.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #e80b0a;">Sorry，浏览器不支持WebSocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button disabled="disabled" id="disconnect" onclick="disconnect();">断开连接</button>
    </div>
    <p></p>
    <div id="conversationDiv">
        <label>输入内容</label><input id="content" type="text"/>
        <button id="sendContent" onclick="sendContent();">发送</button>
        <div id="response"></div>
        <div id="callback"></div>
        <p></p>
        <div id="debug"></div>
    </div>
</div>
<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
        document.getElementById("connect").disabled = connected;
        document.getElementById("disconnect").disabled = !connected;
        document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
        $("#response").html();
        $("#callback").html();
    }

    //创建连接
    function connect() {

        //WebSocket 协议
        var socket = new WebSocket('ws://localhost:8080/webroot/ws');

        //SockJS 协议  浏览器不支持WebSocket协议时，可切换至SockJS协议(后台也要变动)
        // var socket = new SockJS('http://localhost:8080/webroot/ws');
        stompClient = Stomp.over(socket);

        stompClient.heartbeat.outgoing = 20000;  // client will send heartbeats every 20000ms
        stompClient.heartbeat.incoming = 0;

        //debug 日志输出，一般不需要的
        stompClient.debug = function(str) {
            // str 参数即为 debug 信息
            // append the debug log to a #debug div somewhere in the page using JQuery:
            $("#debug").append("<p>"+str + "</p>");
        };

        // 定义客户端的认证信息,按需求配置
        let headers = {
            Authorization: ''
        };

        // stompClient.connect(headers, function (frame) {
        stompClient.connect({}, function (frame) {
            setConnected(true);
            console.log('Connected:' + frame);

            //订阅消息  订阅和接收消息通过 subscribe() 方法
            let subscribe = stompClient.subscribe('/topic/hello', function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
            });

            //取消订阅
            // subscribe.unsubscribe();

            //订阅消息  另外再注册一下定时任务接受
            stompClient.subscribe('/user/123/msg', function (response) {
                showCallback(response.body);
            });


            //消息确认  客户端必须调用message.ack()来通知服务端它已经接收了消息
            var subscription = stompClient.subscribe("/queue/test", function(message) {
                    // do something with the message
                    // and acknowledge it
                    message.ack();
                },
                {ack: 'client'}
            );

        });
    }

    //主动断开连接
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log('Disconnected');
    }

    //发送消息
    function sendContent() {
        var content = $('#content').val();
        console.log('content:' + content);

        /**
         * client.send(destination url, headers, body]);
         *
         * 必须参数   destination url  字符串，是服务器controller中 @MessageMapping中匹配的URL
         * 可选参数   headers    JavaScript 对象，请求头
         * 可选参数   body  字符串，发送信息的 body, 可通过 JSON.stringify() and JSON.parse() 实现传json数据
         *
         * 示例：
         * client.send("/queue/test", {priority: 9}, "Hello, STOMP");
         */
        stompClient.send("/app/hello", {}, JSON.stringify({'content': content}));
    }

    function showResponse(message) {
        $("#response").html(message);
    }

    function showCallback(message) {
        $("#callback").html(message);
    }
</script>
</body>
</html>
